package org.ece3574.WTParty;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class AndroidCamera extends Activity implements SurfaceHolder.Callback{

	Camera camera;
	SurfaceView surfaceView;
	SurfaceHolder surfaceHolder;
	private String selectedImagePath;
	private ImageView img;

	boolean previewing = false;
	LayoutInflater controlInflater = null;
	
	final int RESULT_SAVEIMAGE = 0;
	private static final int SELECT_PICTURE = 1234;

	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.imageview);
        img = (ImageView)this.findViewById(R.id.imageView1);
        img.setClickable(true);
        
        setContentView(R.layout.camera);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        
        getWindow().setFormat(PixelFormat.UNKNOWN);
        surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        
        controlInflater = LayoutInflater.from(getBaseContext());
        View viewControl = controlInflater.inflate(R.layout.control, null);
        LayoutParams layoutParamsControl 
        	= new LayoutParams(LayoutParams.FILL_PARENT, 
        	LayoutParams.FILL_PARENT);
        this.addContentView(viewControl, layoutParamsControl);
        
        Button buttonTakePicture = (Button)findViewById(R.id.takepicture);
        buttonTakePicture.setOnClickListener(new Button.OnClickListener(){

			
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				camera.takePicture(myShutterCallback, 
						myPictureCallback_RAW, myPictureCallback_JPG);
			}});
        Button gallery_ = (Button)findViewById(R.id.gallery);
        gallery_.setOnClickListener(new Button.OnClickListener(){
        	public void onClick(View arg0) {
        		Intent intentBrowseFiles = new Intent();
        		intentBrowseFiles.setType("image/*");
        		intentBrowseFiles.setAction(Intent.ACTION_GET_CONTENT);
        		//final int ACTIVITY_SELECT_IMAGE = 1234;
        		//startActivityForResult(Intent.createChooser(intentBrowseFiles, "Select Picture"),ACTIVITY_SELECT_IMAGE);
                //intentBrowseFiles.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        		startActivityForResult(Intent.createChooser(intentBrowseFiles,
                        "Select Picture"), SELECT_PICTURE);
            }
        	
        });
    }
    
    ShutterCallback myShutterCallback = new ShutterCallback(){

		public void onShutter() {
			// TODO Auto-generated method stub
			
		}};
		
	PictureCallback myPictureCallback_RAW = new PictureCallback(){

		public void onPictureTaken(byte[] arg0, Camera arg1) {
			// TODO Auto-generated method stub
			
		}};
		
	PictureCallback myPictureCallback_JPG = new PictureCallback(){

		
		public void onPictureTaken(byte[] arg0, Camera arg1) {
			// TODO Auto-generated method stub
			/*Bitmap bitmapPicture 
				= BitmapFactory.decodeByteArray(arg0, 0, arg0.length);	*/
			
			Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());

			OutputStream imageFileOS;
			try {
				imageFileOS = getContentResolver().openOutputStream(uriTarget);
				imageFileOS.write(arg0);
				imageFileOS.flush();
				imageFileOS.close();
				
				Toast.makeText(AndroidCamera.this, 
						"Image saved: " + uriTarget.toString(), 
						Toast.LENGTH_LONG).show();
				
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			camera.startPreview();
		}};

	
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub
		if(previewing){
			camera.stopPreview();
			previewing = false;
		}
		
		if (camera != null){
			try {
				camera.setPreviewDisplay(surfaceHolder);
				camera.startPreview();
				previewing = true;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		camera = Camera.open();
	}

	
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		camera.stopPreview();
		camera.release();
		camera = null;
		previewing = false;
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) 
	{
	    super.onActivityResult(requestCode, resultCode, data); 

	    switch(requestCode) { 
	    case 1234:
	        if(resultCode == RESULT_OK){  
	            Uri selectedImage = data.getData();
	            String[] filePathColumn = {MediaStore.Images.Media.DATA};

	            //Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
	            Cursor cursor = managedQuery(selectedImage, filePathColumn, null, null, null);
	            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	            cursor.moveToFirst();

	            //int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
	            //String filePath = cursor.getString(columnIndex);
	            selectedImagePath = cursor.getString(columnIndex);
	            System.out.println("Image Path : " + selectedImagePath);
	            //Bitmap photo = (Bitmap) data.getExtras().get("data");
	            //photo = photo.createScaledBitmap(photo, 80, 80, false);
	            //img.setImageBitmap(photo);
	          /*  try {
					img.setImageDrawable(Drawable.createFromStream(
					        getContentResolver().openInputStream(selectedImage),null));
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}*/
	            //cursor.close();

	            Intent intent = new Intent();
	            intent.setAction(Intent.ACTION_VIEW);
	            intent.setDataAndType(selectedImage, "image/*");
	            startActivity(intent);
	            //Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
	           //img.setBackgroundResource(0);
	           //img.setImageBitmap(yourSelectedImage);


	        }
	    }

	}
	
	
}